using MediatR;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;
using WMS.WebApiRead.DTO;

namespace WMS.WebApiRead.Application.Commandhandler
{
    /// <summary>
    /// 仓库信息查询命令处理器（分页查询+联表查询）
    /// </summary>
    public class WarehouseQueryCommandHandler : IRequestHandler<WarehouseQueryCommand, ApiResult<ApiPaging<List<WarehouseInfoResultDTO>>>>
    {
        private readonly IBaseRepository<WarehouseInfo> warehouseRepository;
        private readonly IBaseRepository<WarehouseSupervisor> supervisorRepository;
        private readonly IBaseRepository<WarehouseDept> deptRepository;

        /// <summary>
        /// 构造函数，注入仓储接口
        /// </summary>
        public WarehouseQueryCommandHandler(
            IBaseRepository<WarehouseInfo> warehouseRepository,
            IBaseRepository<WarehouseSupervisor> supervisorRepository,
            IBaseRepository<WarehouseDept> deptRepository)
        {
            this.warehouseRepository = warehouseRepository;
            this.supervisorRepository = supervisorRepository;
            this.deptRepository = deptRepository;
        }

        /// <summary>
        /// 处理仓库信息查询命令（支持分页、筛选、联表查询）
        /// </summary>
        public async Task<ApiResult<ApiPaging<List<WarehouseInfoResultDTO>>>> Handle(WarehouseQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 联表查询：仓库信息 LEFT JOIN 主管表 LEFT JOIN 部门表
                var query = from warehouse in warehouseRepository.GetAll()
                            where !warehouse.IsDeleted // 只查询未删除的记录
                            join supervisor in supervisorRepository.GetAll()
                            on warehouse.SupervisorId equals supervisor.SupervisorId into supervisorGroup
                            from supervisor in supervisorGroup.DefaultIfEmpty()
                            join dept in deptRepository.GetAll()
                            on warehouse.WarehouseDeptId equals dept.WarehouseDeptId into deptGroup
                            from dept in deptGroup.DefaultIfEmpty()
                            select new
                            {
                                Warehouse = warehouse,
                                SupervisorName = supervisor != null ? supervisor.SupervisorName : "未分配",
                                DeptName = dept != null ? dept.WarehouseDeptName : "未分配"
                            };

                // 条件筛选：仓库名称（模糊查询）
                if (!string.IsNullOrWhiteSpace(request.QueryDTO.WarehouseName))
                {
                    query = query.Where(x => x.Warehouse.WarehouseName.Contains(request.QueryDTO.WarehouseName));
                }

                // 条件筛选：仓库状态
                if (request.QueryDTO.WarehouseState.HasValue)
                {
                    query = query.Where(x => x.Warehouse.WarehouseState == request.QueryDTO.WarehouseState.Value);
                }

                // 条件筛选：仓库主管ID
                if (request.QueryDTO.SupervisorId.HasValue)
                {
                    query = query.Where(x => x.Warehouse.SupervisorId == request.QueryDTO.SupervisorId.Value);
                }

                // 条件筛选：库管部门ID
                if (request.QueryDTO.WarehouseDeptId.HasValue)
                {
                    query = query.Where(x => x.Warehouse.WarehouseDeptId == request.QueryDTO.WarehouseDeptId.Value);
                }

                // 条件筛选：数据状态
                if (request.QueryDTO.DataStatus.HasValue)
                {
                    query = query.Where(x => x.Warehouse.DataStatus == request.QueryDTO.DataStatus.Value);
                }

                // 计算总记录数
                var totalCount = query.Count();

                // 计算总页数
                var totalPage = (int)Math.Ceiling((double)totalCount / request.QueryDTO.PageSize);

                // 执行分页查询并投影到DTO
                var data = query
                    .OrderByDescending(x => x.Warehouse.CreateTime) // 按创建时间倒序
                    .Skip((request.QueryDTO.PageIndex - 1) * request.QueryDTO.PageSize)
                    .Take(request.QueryDTO.PageSize)
                    .Select(x => new WarehouseInfoResultDTO
                    {
                        WarehouseID = x.Warehouse.WarehouseID,
                        WarehouseCode = x.Warehouse.WarehouseCode,
                        WarehouseName = x.Warehouse.WarehouseName,
                        Warehousecapacity = x.Warehouse.Warehousecapacity,
                        SupervisorId = x.Warehouse.SupervisorId,
                        SupervisorName = x.SupervisorName, // 联表查询得到的主管名称
                        WarehouseDeptId = x.Warehouse.WarehouseDeptId,
                        WarehouseDeptName = x.DeptName, // 联表查询得到的部门名称
                        WarehousePhone = x.Warehouse.WarehousePhone,
                        WarehouseAddress = x.Warehouse.WarehouseAddress,
                        WarehouseState = x.Warehouse.WarehouseState,
                        WarehouseLockdown = x.Warehouse.WarehouseLockdown,
                        WarehouseContent = x.Warehouse.WarehouseContent,
                        IsDeleted = x.Warehouse.IsDeleted,
                        DataStatus = x.Warehouse.DataStatus, // 数据状态
                        CreateName = x.Warehouse.CreateName,
                        CreateTime = x.Warehouse.CreateTime,
                        UpdateName = x.Warehouse.UpdateName,
                        UpdateTime = x.Warehouse.UpdateTime,
                        DeleteName = x.Warehouse.DeleteName,
                        DeleteTime = x.Warehouse.DeleteTime
                    })
                    .ToList();

                // 返回分页结果
                return new ApiResult<ApiPaging<List<WarehouseInfoResultDTO>>>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询仓库信息成功",
                    Data = new ApiPaging<List<WarehouseInfoResultDTO>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = data
                    }
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<ApiPaging<List<WarehouseInfoResultDTO>>>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询仓库信息异常：{ex.Message}",
                    Data = new ApiPaging<List<WarehouseInfoResultDTO>>
                    {
                        TotalCount = 0,
                        TotalPage = 0,
                        Data = new List<WarehouseInfoResultDTO>()
                    }
                };
            }
        }
    }
}

